package com.cqhz.quwan.ui.widget

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import com.cqhz.quwan.R
import com.cqhz.quwan.util.CLogger
import com.cqhz.quwan.util.inflate

class StateLayout(
        context: Context?,
        private val attrs: AttributeSet?
) : FrameLayout(context, attrs) {
    private val logger = CLogger(this::class.java)
    private var loadingLayout:ViewGroup? = null
    private var dataNoneLayout:ViewGroup? = null
    private var loadingLayoutId:Int? = null
    private var dataNoneLayoutId:Int? = null
    private var mTarget:View? = null
    init {

        val typedArray = context?.obtainStyledAttributes(attrs,R.styleable.StateLayout)
        loadingLayoutId = typedArray?.getResourceId(R.styleable.StateLayout_loadingLayout,-1)
        dataNoneLayoutId = typedArray?.getResourceId(R.styleable.StateLayout_dataNoneLayout,-1)
        typedArray?.recycle()
        if(loadingLayoutId != null && loadingLayoutId != -1){
            loadingLayout = inflate(loadingLayoutId!!,false) as ViewGroup
        }
        if(dataNoneLayoutId != null && dataNoneLayoutId != -1){
            dataNoneLayout = inflate(dataNoneLayoutId!!,false) as ViewGroup
        }
        if(loadingLayout != null){
            loadingLayout!!.visibility = View.GONE
            addView(loadingLayout)
        }
        if(dataNoneLayout != null){
            dataNoneLayout!!.visibility = View.GONE
            addView(dataNoneLayout)
        }
        mTarget?.visibility = View.VISIBLE
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        ensureTarget()
    }

    private fun ensureTarget() {
        // Don't bother getting the parent height if the parent hasn't been laid
        // out yet.
        if (mTarget == null) {
            for (i in 0 until childCount) {
                val child = getChildAt(i)
                mTarget = when(child){
                    loadingLayout -> null
                    dataNoneLayout -> null
                    else -> child
                }
                if (mTarget != null){
                    break
                }
            }
        }
    }

    fun showDataNoneLayout(){
        dataNoneLayout?.visibility = View.VISIBLE
        loadingLayout?.visibility = View.GONE
        mTarget?.visibility = View.GONE
    }

    fun showLoadingLayout(){
        loadingLayout?.visibility = View.VISIBLE
        dataNoneLayout?.visibility = View.GONE
        mTarget?.visibility = View.GONE
    }

    fun clearLayout(){
        mTarget?.visibility = View.VISIBLE
        loadingLayout?.visibility = View.GONE
        dataNoneLayout?.visibility = View.GONE
    }

}